<template>
  <div class="mod-config">
    <el-form
      :model="dataForm"
      :inline="true"
      :rules="dataRule"
      size="medium "
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <table>
        <tr>
          <td>
            <el-form-item label="项目名称" prop="projectName">
              <el-input
                v-model="dataForm.projectName"
                size="medium"
                placeholder="项目名称"
              ></el-input>
            </el-form-item>
          </td>
          <td>
            <el-form-item label="项目类型" prop="projectTypeName">
              <el-input
                v-model="dataForm.projectTypeName"
                size="medium"
                placeholder="项目类型"
              ></el-input>
            </el-form-item>
          </td>
          <td>
            <el-form-item label="创建日期" prop="createTime">
              <el-date-picker
                v-model="dataForm.createTime"
                type="datetime"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <td>
            <el-form-item label="项目金额" prop="projectAmount">
              <el-input
                v-model="dataForm.projectAmount"
                size="medium"
                placeholder="项目金额"
              ></el-input>
            </el-form-item>
          </td>
          <td>
            <el-form-item label="最终金额" prop="finalProjectAmount">
              <el-input
                v-model="dataForm.finalProjectAmount"
                size="medium"
                placeholder="最终金额"
              ></el-input>
            </el-form-item>
          </td>
          <td>
            <el-form-item label="项目状态" prop="projectStatus">
              <el-select
                v-model="dataForm.projectStatus"
                placeholder="请选择"
                :disabled="chk1"
              >
                <el-option
                  v-for="item in projectList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <td>
            <el-form-item label="所在区域">
              <el-cascader
                v-model="dataForm.provinceCodes"
                :options="optionsList"
                :props="departListTreeProps"
                clearable
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </td>
          <td>
            <el-form-item label="详细地址" prop="address">
              <el-input
                v-model="dataForm.address"
                size="medium"
                placeholder="详细地址"
              ></el-input>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <td>
            <el-form-item label="相关附件" prop="filePath">
              <el-upload
                class="upload-demo"
                :action="url"
                :before-upload="beforeUploadHandle"
                :on-success="successHandle"
                :on-remove="handleRemove"
                :file-list="fileList"
              >
                <el-button size="small" type="primary">附件上传</el-button>
                <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500mb</div> -->
              </el-upload>
            </el-form-item>
          </td>
        </tr>
        <!-- <tr>
      <td>
     <el-form-item label="文件路径" prop="filePath">
       <span>{{dataForm.filePath}}</span> 
      </el-form-item>
      </td>
    </tr> -->
      </table>
      <el-form-item label="项目描述" class="coment">
        <quill-editor
          v-model="dataForm.projectDescription"
          ref="myQuillEditor"
          class="ql-editor-class"
          :options="editorOption"
        >
        </quill-editor>
      </el-form-item>

      <!-- <el-form-item label="创建人id" prop="createUserId">
      <el-input v-model="dataForm.createUserId" placeholder="创建人id"></el-input>
    </el-form-item> -->

      <!-- <el-form-item label="市code" prop="cityCode">
      <el-input v-model="dataForm.cityCode" placeholder="市code"></el-input>
    </el-form-item>
    <el-form-item label="区code" prop="districtCode">
      <el-input v-model="dataForm.districtCode" placeholder="区code"></el-input>
    </el-form-item> -->
      <!-- </table> -->
    </el-form>
    <span slot="footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </div>
</template>

<script>
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { treeDataTranslate } from "@/utils";
import configAddOrUpdateVue from "../sys/config-add-or-update.vue";
export default {
  data() {
    return {
      visible: false,
      dataForm: {
        projectId: 0,
        projectName: "",
        projectTypeName: "",
        projectDescription: "",
        createTime: "",
        projectStatus: "",
        createUserId: "",
        fileName: "",
        filePath: "",
        projectAmount: "",
        finalProjectAmount: "",
        provinceCode: "",
        cityCode: "",
        districtCode: "",
        coment: "",
        address: "",
        provinceCodes: [],
      },
      info: {},
      optionsList: [],
      departListTreeProps: {
        label: "name",
        children: "children",
        value: "id",
      },
      projectList: [
        {
          label: "立项",
          value: "0",
        },
        {
          label: "正在进行中",
          value: "1",
        },
        {
          label: "归档",
          value: "2",
        },
      ],
      optyp: "",
      num: 0,
      successNum: 0,
      fileList: [],
      editorOption: {},
      url: "",
      chk1: false,
      dataRule: {
        projectName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" },
        ],
        projectTypeName: [
          { required: true, message: "项目类型名称不能为空", trigger: "blur" },
        ],
        projectDescription: [
          { required: true, message: "项目描述不能为空", trigger: "blur" },
        ],
        createTime: [
          { required: true, message: "创建日期不能为空", trigger: "blur" },
        ],
        projectStatus: [
          { required: true, message: "项目状态不能为空", trigger: "blur" },
        ],
        // createUserId: [
        //   { required: true, message: '创建人id不能为空', trigger: 'blur' }
        // ],
        // filePath: [
        //   { required: true, message: '文件路径不能为空', trigger: 'blur' }
        // ],
        // projectAmount: [
        //   { required: true, message: '项目金额不能为空', trigger: 'blur' }
        // ],
        // finalProjectAmount: [
        //   { required: true, message: '最终项目金额不能为空', trigger: 'blur' }
        // ],
        // provinceCode: [
        //   { required: true, message: '省不能为空', trigger: 'blur' }
        // ],
        // cityCode: [
        //   { required: true, message: '市不能为空', trigger: 'blur' }
        // ],
        // districtCode: [
        //   { required: true, message: '所在区域不能为空', trigger: 'blur' }
        // ]
      },
    };
  },
  components: {
    quillEditor,
  },
  activated() {
    this.init();
  },
  mounted() {
    this.chain();
  },
  methods: {
    init() {
      this.info = this.$route.params.info;
      this.url = this.$http.adornUrl(
        `/sys/oss/upload?token=${this.$cookie.get("token")}`
      );
      this.visible = true;
      if (null != this.info) {
        this.fileList = [{ name: "" }];
        this.dataForm.projectId = this.info.id || 0;
        // this.visible = true
        this.$nextTick(() => {
          this.$refs["dataForm"].resetFields();
          if (this.dataForm.projectId) {
            this.$http({
              url: this.$http.adornUrl(
                `/business/project/info/${this.dataForm.projectId}`
              ),
              method: "get",
              params: this.$http.adornParams(),
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.dataForm.projectName = data.project.projectName;
                this.dataForm.projectTypeName = data.project.projectTypeName;
                this.dataForm.projectDescription =
                  data.project.projectDescription;
                this.dataForm.createTime = data.project.createTime;

                this.dataForm.projectStatus = data.project.projectStatus + "";
                if (this.dataForm.projectStatus == "1") {
                  this.chk1 = true;
                }
                this.dataForm.createUserId = data.project.createUserId;
                if (data.project.fileName != null) {
                  this.fileList[0].name = data.project.fileName;
                } else {
                  this.fileList = [];
                }

                this.dataForm.filePath = data.project.filePath;
                this.dataForm.projectAmount = data.project.projectAmount;
                this.dataForm.finalProjectAmount =
                  data.project.finalProjectAmount;
                this.dataForm.address = data.project.address;
                var provinceCodes = [];
                provinceCodes.push(data.project.provinceCode);
                provinceCodes.push(data.project.cityCode);
                provinceCodes.push(data.project.districtCode);
                console.log("provinceCodes" + JSON.stringify(provinceCodes));
                this.dataForm.provinceCodes = provinceCodes;
              }
            });
          }
        });
      } else {
        //文件上传置空
        this.fileList = [];
      }
    },
    chain() {
      this.$http({
        url: this.$http.adornUrl("business/china/list-tree"),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          // console.log(JSON.stringify(data.page))
          this.optionsList = data.page;
          //  console.log(JSON.stringify(this.optionsList))
        } else {
          this.optionsList = [];
        }
      });
    },
    //删除
    handleRemove(file, fileList) {
      console.log(file.name, fileList);
      this.$http({
        url: this.$http.adornUrl("sys/oss/delete-file"),
        method: "post",
        params: this.$http.adornParams({
          filePath: file.name,
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: "删除成功",
            type: "success",
            duration: 1500,
            onClose: () => {},
          });
        }
      });
      // this.$axios.post('/api/delete',file.name ) //请求头要为表单
      //   .then(response=>{
      //     console.log(response.data);
      //   })
      //   .catch(function (error) {
      //     console.log(error);
      //   })
    },
    // 上传成功
    successHandle(response, file, fileList) {
      this.fileList = fileList;
      console.log(JSON.stringify(fileList));
      this.dataForm.filePath = response.url;
      this.dataForm.fileName = fileList[0].name;
      this.successNum++;
      if (response && response.code === 0) {
        this.$message({
          message: "上传成功",
          type: "success",
          duration: 1500,
          onClose: () => {},
        });
        // if (this.num === this.successNum) {
        //   this.$confirm('操作成功, 是否继续操作?', '提示', {
        //     confirmButtonText: '确定',
        //     cancelButtonText: '取消',
        //     type: 'warning'
        //   }).catch(() => {
        //     this.visible = false
        //   })
        // }
      } else {
        this.$message.error(response.msg);
      }
    },
    fromtStr(str) {
      if (str != null) {
        return str.replace(/<[^>]+>/g, "");
      }
      return "";
    },
    fromtYN(value) {
      if (value == "0") {
        return "立项";
      } else if (value == "1") {
        return "正在进行中";
      } else if (value == "2") {
        return "归档";
      }
      return "";
    },
    handleChange(provinceCodes) {
      console.log("provinceCodes" + JSON.stringify(provinceCodes));
    },
    // 上传之前
    beforeUploadHandle(file) {
      // if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
      //   this.$message.error('只支持jpg、png、gif格式的图片！')
      //   return false
      // }
      this.num++;
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/business/project/${
                !this.dataForm.projectId ? "save" : "update"
              }`
            ),
            method: "post",
            data: this.$http.adornData({
              projectId: this.dataForm.projectId || undefined,
              projectName: this.dataForm.projectName,
              projectTypeName: this.dataForm.projectTypeName,
              projectDescription: this.fromtStr(
                this.dataForm.projectDescription
              ),
              createTime: this.dataForm.createTime,
              projectStatus: this.dataForm.projectStatus,
              createUserId: this.dataForm.createUserId,
              fileName: this.dataForm.fileName,
              filePath: this.dataForm.filePath,
              projectAmount: this.dataForm.projectAmount,
              finalProjectAmount: this.dataForm.finalProjectAmount,
              provinceCode: this.dataForm.provinceCodes[0],
              cityCode: this.dataForm.provinceCodes[1],
              districtCode: this.dataForm.provinceCodes[2],
              address: this.dataForm.address,
            }),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
              this.dataForm = {};
              this.fileList = [];
            } else {
              this.$message.error(data.msg);
              this.dataForm = {};
            }
          });
        }
      });
    },
  },
};
</script>

<style type="text/less"  lang="scss" >
.ql-editor-class {
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  line-height: 1.42;
  height: 100%;
  outline: none;
  padding: 0 !important;
  tab-size: 4;
  width: 80%;
  -moz-tab-size: 4;
  text-align: left;
  word-wrap: break-word;
  float: right;
  transform: translateY(-25%); /**上移元素**/
  -ms-transform: translateY(-25%);
  -webkit-transform: translateY(-25%);
  transform: translateX(-20%); /**左移元素**/
  -ms-transform: translateX(-20%);
  -webkit-transform: translateX(-20%);
  //内容框高度
  .ql-container.ql-snow {
    height: 300px;
  }
}
</style>